from django.db.models import Q

from base import errors
from base import controllers as base_ctl
from account.models import HostModel
from account.models import UserModel
from utils import time_utils


def create_host(name, ip):
    '''
    创建主机
    '''
    obj = HostModel.objects.filter(ip=ip).first()
    data = {
        'name': name,
        'ip': ip,
    }
    if obj:
        base_ctl.update_obj(HostModel, obj.id, data)
    else:
        base_ctl.create_obj(HostModel, data)


def update_host(obj_id, name, ip):
    '''
    编辑主机
    '''
    obj = base_ctl.get_obj(HostModel, obj_id)
    data = {
        'name': name,
        'ip': ip,
    }
    base_ctl.update_obj(HostModel, obj_id, data)


def delete_host(obj_id, operator=None):
    '''
    删除主机
    '''
    HostModel.objects.filter(id=obj_id).delete()


def get_hosts(keyword=None, page_num=None, page_size=None):
    '''
    获取主机列表
    '''
    base_query = HostModel.objects
    if keyword:
        base_query = base_query.filter(Q(name__icontains=keyword)|
                                       Q(ip__icontains=keyword))
    base_query = base_query.order_by('ip')
    total = base_query.count()
    objs = base_ctl.query_objs_by_page(base_query, page_num, page_size)
    data_list = []
    for obj in objs:
        data = obj.to_dict()
        # TODO: 增加在线状态角色数
        data_list.append(data)
    data = {
        'total': total,
        'data_list': data_list,
    }
    return data


def get_host(obj_id, operator=None):
    '''
    获取主机信息
    '''
    obj = base_ctl.get_obj(HostModel, obj_id)
    data = obj.to_dict()
    return data